// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  let { id } = event
  var success = false
  var message = "撤销打卡失败"
  const db = cloud.database()
  var cards = await db.collection('cards').where({
    _id: id
  }).get()

  console.log('cards', cards)
  console.log('id', id)
  if (cards.data.length != 0) {
    await db.collection('cards').where({
      _id: id
    }).update({
      data: {
        status: "unChecked"
      }
    }).then(res => {
      console.log('res', res)
      success = true
      message = "撤销打卡成功"
    }, error => {
      console.log('error', error)
      success = false
      message = "撤销打卡失败，请联系管理员"
    })
  }

  let card = cards.data[0];
  if (success && card.status == 'checked') {
    let user = await db.collection('user').where({
      _openid: card._openid
    }).get()
    let point = user.data[0].point - card.point;
    await db.collection('user').where({
      _openid: card._openid
    }).update({
      data: {
        point: point
      }
    }).then(res => {
      console.log('res', res)
      success = true
      message = "撤销打卡成功"
    }, error => {
      console.log('error', error)
      success = false
      message = "撤销打卡失败，请联系管理员"
    })
  }

  var userData = await db.collection('userInfo').where({
    _openid: card._openid
  }).get()

  let userInfo = userData.data[0]
  var distance = card.distance;
  if (!distance) {
    distance = 0
  }
  var time = card.time;
  if (!time) {
    time = 0
  }
  var calorie = card.calorie;
  if (!calorie) {
    calorie = 0
  }

  if (success && card.status == 'checked' && userInfo) {
    if (userInfo.distance) {
      distance = parseFloat(userInfo.distance) - parseFloat(distance)
      distance = distance.toFixed(2)
    }
    if (userInfo.time) {
      time = parseInt(userInfo.time) - parseInt(time)
    }
    if (userInfo.calorie) {
      calorie = parseInt(userInfo.calorie) - parseInt(calorie)
    }
    point = parseInt(userInfo.point) - parseInt(card.point)
    await db.collection('userInfo').where({
      _openid: card._openid
    }).update({
      data: {
        point: point,
        distance: distance,
        calorie: calorie,
        time: time
      },
    }).then(res => {
      console.log('res', res)
      success = true
      message = "撤销打卡成功"
    }, error => {
      console.log('error', error)
      success = false
      message = "撤销打卡失败，请联系管理员"
    })
  }
  return {
    success: success,
    message: message
  }
}